<template>
  <div class="create-page">
    <div class="inner-container">
      <div class="header-box">
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键词" prop="keyword">
            <el-input v-model="searchForm.keyword" placeholder="请输入关键词" />
          </el-form-item>
          <el-form-item>
            <el-button v-permission="'systemRole:search'" type="primary" @click="submitForm('searchForm')">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="formCancel('searchForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row>
          <el-col :span="2">
            <el-button v-permission="'systemRole:new'" type="primary" @click="add">新增角色</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="table-container">
        <div class="table-box">
          <el-table
            :data="contentData"
            border
            :header-cell-style="{textAlign:'center'}"
            :cell-style="{textAlign:'center'}"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" fixed />
            <el-table-column prop="name" label="角色名" />
            <el-table-column prop="code" label="唯一编码" />
            <el-table-column prop="sort" label="排序" />
            <el-table-column label="操作" width="240" fixed="right">
              <template slot-scope="scope">
                <a v-permission="'systemRole:edit'" @click="edit(scope.row)"><i class="el-icon-edit" /> 编辑</a>
                <el-divider direction="vertical" content-position="center" />
                <a>
                  <el-dropdown @command="clickCommand($event,scope.row)">
                    <span class="el-dropdown-link">
                      更多<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-permission="'systemRole:menu'" command="授权菜单">授权菜单</el-dropdown-item>
                      <el-dropdown-item v-permission="'systemRole:delete'" command="删除">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </a>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-pagination">
          <!-- 分页 -->
          <el-pagination
            :page-sizes="[10, 20, 50, 100]"
            :page-size="params.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-drawer
      v-if="visible"
      title="授权菜单"
      :visible.sync="visible"
      direction="rtl"
      :before-close="closeDrawer"
    >
      <div class="tree-box">
        <!-- check-strictly -->
        <!-- :default-checked-keys="defaultSelect" -->
        <el-tree
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          :default-checked-keys="defaultSelect"
          node-key="id"
          show-checkbox
          :check-strictly="true"
          default-expand-all
          class="filter-tree"
          @check-change="handleCheckChange"
        />
      </div>
      <div class="tree-button">
        <el-button style="margin-right:20px;" @click="visible = false">取消</el-button>
        <el-button type="primary" @click="setTree">确定</el-button>
      </div>
    </el-drawer>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="20%"
    >
      <span>是否确定删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDel">确 定</el-button>
      </span>
    </el-dialog>
    <editRole ref="editRole" @reload="reload" />
  </div>
</template>
<script>
import { GetRoleList, GetGrantTree, GetRoleMenu, SetGrantMenu, DelRole } from '@/api/system';
import editRole from '@/components/system/editRole.vue';
import { Loading } from 'element-ui';
export default {
  name: 'SystemRole',
  components: {
    editRole
  },
  props: {},
  data() {
    return {
      searchForm: {},
      rules: {
        keyword: [
          { required: true, message: '关键词不能为空', trigger: 'blur' }
        ]
      },
      contentData: [],
      pageSize: 10,
      params: {
        current: 1,
        size: 10,
        sortFields: 'id',
        sortOrders: 'desc'
      },
      total: 0,
      visible: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      id: '',
      defaultSelect: [],
      selectList: [],
      dialogVisible: false
    }
  },
  computed: {},
  watch: {
  },
  created() {
    this.initData(this.params)
  },
  mounted() {},
  methods: {
    initData(params) {
      GetRoleList(params).then(res => {
        if (res.success) {
          const { data } = res
          this.contentData = data.records
          this.total = data.total
        }
      })
    },
    reload() {
      const requestBody = {
        ...this.params
      }
      this.initData(requestBody)
    },
    setTree() {
      Loading.service({ fullscreen: true });
      const param = {
        id: this.id,
        ids: this.selectList
      }
      SetGrantMenu(param).then(res => {
        res.success && this.$message({
          message: res.msg,
          type: 'success'
        })
        this.visible = false
        Loading.service({ fullscreen: true }).close();
        this.reload()
      }).catch(err => {
        console.log('ooo', err)
        this.visible = false
        Loading.service({ fullscreen: true }).close();
        this.reload()
      })
    },
    submitForm() {
      this.params = Object.assign(this.params, this.searchForm)
      this.initData(this.params)
    },
    formCancel() {
      this.$refs.searchForm.resetFields();
    },
    add() {
      this.$refs.editRole.add()
    },
    edit(row) {
      this.id = row.id
      this.$refs.editRole.edit(row)
    },
    getDeaf(data, list, arr) {
      for (const item of list) {
        if (data.includes(item.id) && !item.children) {
          arr.push(item.id)
        } else {
          if (item.children) {
            this.getDeaf(data, item.children, arr)
          }
        }
      }
    },
    async clickCommand(e, row) {
      this.id = row.id
      if (e === '授权菜单') {
        await GetGrantTree({ tenantId: -1 }).then(res => {
          this.treeData = res.data.tree
          this.defaultSelect = []
          this.selectList = []
        })
        GetRoleMenu({ id: row.id }).then(res => {
          // const newArr = []
          const that = this
          // that.getDeaf(res.data, that.treeData, newArr)
          that.defaultSelect = res.data
          that.selectList = res.data
          that.visible = true
        })
      } else {
        this.dialogVisible = true
      }
    },
    confirmDel() {
      DelRole({ ids: this.id }).then(res => {
        res.success && this.$message({
          message: res.msg,
          type: 'success'
        })
        this.dialogVisible = false
        this.reload()
      })
    },
    filterKey(arr, list) {
      arr.forEach((item) => {
        list.push(item.id);
        item.children && this.filterKey(item.children, list);
      });
      return list
    },
    // checkNode(){
    //   console.log('jjjjjjjjj')
    // },
    handleCheckChange(node, checked, childChecked) {
      const checkNode = this.$refs['tree'].getCheckedNodes()
      console.log('oooooo', checkNode)
      if (checked) {
        this.defaultSelect.push(node.id)
        let newArr = []
        node.children && (newArr = this.filterKey(node.children, []))
        this.defaultSelect = this.defaultSelect.concat(newArr)
        this.defaultSelect = [...new Set(this.defaultSelect)]
      } else {
        // eslint-disable-next-line eqeqeq
        this.defaultSelect = this.defaultSelect.filter(item => item != node.id)
      }
      this.selectList = this.defaultSelect

      // this.selectList = []
      // const childrenNode = this.$refs['tree'].getCheckedNodes()
      // const parentNode = this.$refs['tree'].getHalfCheckedKeys()
      // console.log('childrenNode', childrenNode)
      // console.log('parentNode', parentNode)
      // childrenNode.forEach(v => {
      //   this.selectList.push(v.id)
      // })
      // this.selectList = this.selectList.concat(parentNode)
      // console.log('mmmmm', this.selectList)
    },
    closeDrawer() {
      this.visible = false
    },
    handleSelectionChange() {

    },
    handleSizeChange(e) {
      this.params.size = e;
      this.initData(this.params)
    },
    handleCurrentChange(e) {
      this.params.current = e
      this.initData(this.params)
    }
  }
}
</script>

<style scoped lang="scss">
.create-page {
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;
  .inner-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .header-box{
      width: 100%;
      background-color: #fff;
      padding: 10px 15px;
      ::v-deep .el-form-item{
        margin-right: 30px;
        .el-form-item__label{
          font-family: "Microsoft YaHei";
          color: #333
        }
      }
    }
    .table-container{
      width: 100%;
      border-top: 10px #f0f0f0 solid;
      flex: 1;
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      .table-box {
        width: 100%;
        flex-grow: 1;
        overflow: hidden;
        overflow-y: auto;
        a, .el-dropdown-link{
          color: #409EFF;
        }
      }
      .table-pagination{
        height: 60px;
        width: 100%;
        text-align: right;
        background-color: #fff;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        ::v-deep .el-pagination{
          span, button, ul>li{
            height: 50px;
            line-height: 50px;
            font-size: 16px;
          }
        }
      }
    }
  }
}
  .tree-box{
      width: 100%;
      height: calc(100% - 100px);
      overflow: scroll;
      position: relative;
      padding-bottom: 100px;
    }
    .tree-button{
        width: 100%;
        height: 80px;
        padding: 20px;
        background: white;
        position: absolute;
        bottom: 0px;
        left: 0;
        z-index: 999;
      }
   ::v-deep .el-drawer__body{
      overflow: scroll !important;
    }
</style>
